<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
<!--  高级查询，关键字查找      -->
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getHighLevelDics">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="dics"  highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" >
			</el-table-column>
			<el-table-column prop="name" label="数字字典名" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="编号" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--  分页    -->
			<el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="page"
                     :total="total"
                     style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="dicFormVisible" :close-on-click-modal="false">
			<el-form :model="dicForm" label-width="80px" :rules="dicFormRules" ref="dicForm">
        <el-form-item label="编号" prop="sn">
          <el-input v-model="dicForm.sn" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="数字字典名" prop="name">
					<el-input v-model="dicForm.name" auto-complete="off"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="dicFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="dicSubmit" :loading="dicLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDicListPage, removeDic, batchRemoveDic, dicDic, addDic } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
          keyword: ''
          // table: false
				},
				dics: [],
        employees: [],
        // gridData: [],
        deptTree: [],
				total: 0,
				page: 1,
        pageSize:3,
        title:'',
				listLoading: false,
				sels: [],//列表选中列

				dicFormVisible: false,//编辑界面是否显示
				dicLoading: false,
        /*自定义验证规则*/
				dicFormRules: {
					name: [
            /*trigger: 'blur'：鼠标焦点离开触发*/
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				dicForm: {
          id: null,
          sn:'',
          name: ''
          // state: 0,
          // manager: null,
          // parent: null
				},
			}
		},
		methods: {
			//性别显示转换
			// formatSex: function (row, column) {
			// 	return row.state === 0 ? '<font color="green">启用</font>' : row.state === -1 ? '禁用' : '未知';
			// },
			handleCurrentChange(val) {
				this.page = val;
				this.getDics();
			},
      //解决高级查询的方法
      getHighLevelDics(){
        //高级查询直接写死第一页
        this.page = 1;
        this.getDics()
      },
			//获取部门列表
			getDics() {
				let para = {
					currentPage: this.page,
          keyword: this.filters.keyword,
          pageSize:3
				};
        //开启加载框
				this.listLoading = true;
				//NProgress.start();
        //1.去获取后台系统（8080）的数据
        this.$http.post("/dic",para).then(result=>{   //result.data = pageList对象
            //关闭加载框
            this.listLoading = false;
            console.log(result);
            result = result.data;//pageList对象
            this.dics = result.rows;
            this.total = result.total;
            //解决第二页数据高级查询或都删除后返回第一页的问题
            // this.page=1;
          //写一个算法来让在当前页操作后仍然在当前页，新增修改，删除等，
          if((this.total%this.pageSize) === 0 && (this.total/this.pageSize) < this.page){
            this.page=this.total/this.pageSize
            this.getDics()
          }
         /* if(result.total-this.total===1){
            this.page=this.total/this.pageSize
            console.log(this.page)
            this.getDics()
          }*/

        }).catch(result=>{

        })

				/*getDicListPage(para).then((res) => {
					this.total = res.data.total;
					this.dics = res.data.dics;
          //关闭加载框
					this.listLoading = false;
					//NProgress.done();
				});*/
			},
      //获取产品的下一级内容
      // gridData() {
      //   //1.去获取后台系统（8080）的数据
      //   this.$http.get("/emp").then(result=>{   //result.data = pageList对象
      //       console.log(result);
      //       result = result.data;//List<Employee>对象
      //       this.gridData = result;
      //   })
      // },
			// //获取用户列表
      // getEmployees() {
      //   //1.去获取后台系统（8080）的数据
      //   this.$http.get("/emp").then(result=>{   //result.data = pageList对象
      //       console.log(result);
      //       result = result.data;//List<Employee>对象
      //       this.employees = result;
      //   })
			// },
			//获取部门上下级列表
      // getDeptTree() {
      //   //1.去获取后台系统（8080）的数据
      //   this.$http.get("/dept/tree").then(result=>{   //result.data = pageList对象
      //       console.log(result);
      //       result = result.data;//List<Employee>对象
      //       this.deptTree = result;
      //       console.log(result)
      //   })
			// },
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
          //开启加载框
					this.listLoading = true;
					//NProgress.start();
					// let para = { id: row.id }; /dept/1
          this.$http.delete("/dic/" + row.id).then(result => {
              result = result.data;  //取到AjaxResult
            //关闭加载框
            this.listLoading = false;
            if (result.success){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              // this.page = 1;
              this.getDics();
            }else {
              this.$message({
                message: result.message,
                type: 'error'
              });
              // this.page = 1;
              this.getDics();
            }
          }).catch(result => {
            //关闭加载框
            this.listLoading = false;
            //表示后台出错了
            this.$message({
              message: '系统异常',
              type: 'error'
            });
            // this.page = 1;
            this.getDics();
          });


          /*removeDic(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDics();
					});*/
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        // this.getDeptTree();
        this.title="编辑"
				this.dicFormVisible = true;
        // Object.assign({}, row);：  克隆row行数数，到json对象中
				this.dicForm = Object.assign({}, row);
        //回显上级部门
        // let dirPath = this.dicForm.dirPath;  //   /1/7/39
        // console.log(dirPath)
        // if (dirPath){
        //   let array = dirPath.split("/");//["","1","7","39"]
        //   let parent = [];
        //   //循环
        //   for (let i = 1; i < array.length - 1; i++) {
        //     parent.push(parseInt(array[i])); //["1","7"]=>[1,7]
        //   }
        //   this.dicForm.parent = parent;
        // }
        // console.log(this.dicForm)
			},
			//显示新增界面
			handleAdd: function () {
        // this.getDeptTree();
        this.title="新增"
				this.dicFormVisible = true;
				this.dicForm = {
          id: null,
          sn:'',
          name: ''
          // state: 0,
          // manager: null,
          // parent: null
				};
			},
			//新增或编辑
			dicSubmit: function () {
				this.$refs.dicForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.dicLoading = true;
							//NProgress.start();
              //Object.assign 克隆数据
							let para = Object.assign({}, this.dicForm);
              //1.判断parent有值  //处理空值报400的业务bug
              // if(!para.manager){
              //   para.manager={"id":null};
              // }
              // //1.判断选了父部门
              // let parent=para.parent;
              // if(parent){ //[2,12]   //[2]  //[2,12,17]
              //   let pardeptId=parent[parent.length-1];
              //   console.log(pardeptId)
              //   para.parent={"id":pardeptId};
              // }

							// para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
              //调用后台的新增或修改的方法
              this.$http.put("/dic",para).then(result => {
                result = result.data;  //取到AjaxResult
                //关闭弹出框
                this.dicFormVisible = false;
                //关闭加载框
                this.dicLoading = false;
                if (result.success){
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  });
                  // this.page = 1;
                  this.getDics();
                }else {
                  this.$message({
                    message: result.message,
                    type: 'error'
                  });
                  // this.page = 1;
                  this.getDics();
                }
              }).catch(result => {
                //关闭弹出框
                this.dicFormVisible = false;
                //关闭加载框
                this.dicLoading = false;
                //表示后台出错了
                this.$message({
                  message: '系统异常',
                  type: 'error'
                });
                // this.page = 1;
                this.getDics();
              });






              /*dicDic(para).then((res) => {
                this.dicLoading = false;
                //NProgress.done();
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['dicForm'].resetFields();
                this.dicFormVisible = false;
                this.getDics();
              });*/
						});
					}
				});
			},

			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
        console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					// let para = { ids: ids };
          // console.log(para)
					//调用后台的批量删除的方法
          this.$http.patch("/dic",ids).then(result => {
            result = result.data;  //取到AjaxResult
            //关闭加载框
            this.listLoading = false;
            if (result.success){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              // this.page = 1;
              this.getDics();
            }else {
              this.$message({
                message: result.message,
                type: 'error'
              });
              // this.page = 1;
              this.getDics();
            }
          }).catch(result => {
            //关闭加载框
            this.listLoading = false;
            //表示后台出错了
            this.$message({
              message: '系统异常',
              type: 'error'
            });
            // this.page = 1;
            this.getDics();
          });



          /*batchRemoveDic(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getDics();
					});*/
				}).catch(() => {

				});
			}
		},
    /*钩子函数*/
		mounted() {
			this.getDics();
			// this.getEmployees();
		}
	}

</script>

<style scoped>

</style>